
// tech_news_aggregator/frontend/js/news-loader.js
const NEWS_API_URL = 'https://hacker-news.firebaseio.com/v0';
const CACHE_KEY = 'tech_news_cache';
const LAST_UPDATED_KEY = 'tech_news_last_updated';
const CACHE_EXPIRY = 6 * 60 * 60 * 1000; // 6小时缓存

async function fetchTopStories() {
  try {
    const response = await fetch(`${NEWS_API_URL}/topstories.json`);
    const storyIds = await response.json();
    const topStoryIds = storyIds.slice(0, 30); // 获取前30条
    
    const stories = await Promise.all(
      topStoryIds.map(async id => {
        const storyResponse = await fetch(`${NEWS_API_URL}/item/${id}.json`);
        return storyResponse.json();
      })
    );
    
    return stories.map(story => ({
      id: story.id,
      title: story.title,
      url: story.url || `https://news.ycombinator.com/item?id=${story.id}`,
      time: new Date(story.time * 1000).toISOString(),
      score: story.score || 0,
      descendants: story.descendants || 0,
      by: story.by,
      source: 'Hacker News',
      category: '人工智能' // 默认分类，实际应从内容分析
    }));
  } catch (error) {
    console.error('Failed to fetch Hacker News:', error);
    return [];
  }
}

async function fetch36KrNews() {
  try {
    const response = await fetch('https://36kr.com/pp/api/aggregation-entity?per_page=20');
    const data = await response.json();
    
    return data.data.items.map(item => ({
      id: item.id,
      title: item.title,
      url: `https://36kr.com/p/${item.id}`,
      summary: item.summary,
      time: item.published_at,
      source: '36氪',
      category: item.tag || '其他'
    }));
  } catch (error) {
    console.error('Failed to fetch 36Kr news:', error);
    return [];
  }
}

async function loadNews() {
  const cachedNews = localStorage.getItem(CACHE_KEY);
  const lastUpdated = localStorage.getItem(LAST_UPDATED_KEY);
  
  if (cachedNews && lastUpdated && (Date.now() - parseInt(lastUpdated)) < CACHE_EXPIRY) {
    return JSON.parse(cachedNews);
  }
  
  const [hackerNews, kr36News] = await Promise.all([
    fetchTopStories(),
    fetch36KrNews()
  ]);
  
  const allNews = [...hackerNews, ...kr36News]
    .sort((a, b) => new Date(b.time) - new Date(a.time));
  
  localStorage.setItem(CACHE_KEY, JSON.stringify(allNews));
  localStorage.setItem(LAST_UPDATED_KEY, Date.now().toString());
  
  return allNews;
}

function scheduleRefresh() {
  // 每6小时刷新一次
  setInterval(async () => {
    console.log('Refreshing news data...');
    await loadNews();
    window.dispatchEvent(new Event('newsUpdated'));
  }, CACHE_EXPIRY);
}

// 初始化加载并设置定时刷新
(async function init() {
  await loadNews();
  scheduleRefresh();
})();

export { loadNews };
